<template>
  <div class="page">
    <div class="box-content w-1376">
      <main-card-admin :title="datasetName || ''" :crumbs="crumbs" :loading="detailLoading">
        <template #tool-btn>
          <a-button v-if="checkPermissions(detailInfo?.createType, detailInfo?.readOnly)" type="primary" @click="addVersion"
            >新建版本</a-button
          >
        </template>
        <template #screen-space>
          <div class="fbc">
            <a-select
              v-model:value="pageForm.source"
              class="w-140"
              :options="[{ label: '全部来源', value: '' }, ...sourceOptions]"
              @change="getDetailsListData({ offset: 1 })"
            />
            <div class="flex-1"></div>
            <g-input
              v-model:value="pageForm.version"
              v-trim
              class="h-36"
              allow-clear
              :search="true"
              placeholder="请输入版本号"
              style="width: 328px"
              @keyup.enter="getDetailsListData({ offset: 1 })"
            />
          </div>
        </template>
        <div class="page mt-32">
          <a-table
            :style="{ width: '100%' }"
            :pagination="false"
            :columns="tableColumns"
            :data-source="detailList"
            :row-key="(record:IUser) => record.id"
            @change="tableChange"
          >
            <template #bodyCell="{ column, record }">
              <template v-if="column.dataIndex === 'source'">
                {{ sourceOptions.find((item: any) => item.value === record.source)?.label || '' }}
              </template>
              <template v-else-if="column.dataIndex == 'createTime'">
                {{ dateFormat(record.createTime) }}
              </template>

              <template v-else-if="column.dataIndex == 'tools'">
                <!-- <div @click.stop="">
                  <a-button
                    v-if="checkPermissions(detailInfo?.createType, detailInfo?.readOnly)"
                    type="link"
                    class="mr-16"
                    @click="handleUser(record, 'edit')"
                    >编辑</a-button
                  >
                  <a-button type="link" class="mr-16" @click="handleUser(record, 'download')">下载</a-button>
                  <a-button
                    v-if="record.isVisualize"
                    type="link"
                    class="mr-16"
                    :disabled="!record.isVisualize"
                    @click="handleUser(record, 'preview')"
                  >
                    可视化
                  </a-button>
                  <a-button
                    v-if="checkPermissions(detailInfo?.createType, detailInfo?.readOnly)"
                    type="link"
                    class="mr-16"
                    @click="handleUser(record, 'delete')"
                  >
                    删除
                  </a-button>
                </div> -->
                <a-dropdown placement="bottom" @click.stop>
                  <a-button :data-share="record?.createType === 1" type="text" class="icon-only-btn" @click.stop>
                    <i class="iconfont icon-more-line"></i>
                  </a-button>
                  <template #overlay>
                    <a-menu>
                      <a-menu-item class="menu-icon-item" @click="operation(1, record)"> 下载 </a-menu-item>
                      <a-menu-item class="menu-icon-item" @click="operation(2, record)"> 在线部署 </a-menu-item>
                      <a-menu-item class="menu-icon-item" @click="operation(3, record)"> 离线部署 </a-menu-item>
                      <a-menu-item
                        v-if="checkPermissions(detailInfo?.createType, detailInfo?.readOnly)"
                        class="menu-icon-item"
                        @click="operation(4, record)"
                      >
                        删除
                      </a-menu-item>
                      <a-menu-item class="menu-icon-item" @click="operation(5, record)"> 模型评估 </a-menu-item>
                    </a-menu>
                  </template>
                </a-dropdown>
              </template>
              <template v-else>
                <span> {{ replaceEmptyStr(record[column.dataIndex as string]) }} </span>
              </template>
            </template>
          </a-table>
        </div>
        <g-pagination
          v-model:offset="pageForm.offset"
          v-model:limit="pageForm.limit"
          :total="pageForm.total"
          @change="getDetailsListData()"
        />
      </main-card-admin>
    </div>
  </div>
  <offline-deployment-modal ref="offlineDeploymentModalRef" />
  <addVersionModal ref="addVersionModalRef" :after-close-fn="getDetailsListData" />
  <modelEvaluationModal ref="modelEvaluationModalRef" />
</template>
<script setup lang="ts">
  import { message, Modal, TableProps } from 'ant-design-vue'
  import { dateFormat } from 'g6-fn'
  import { computed, ref } from 'vue'
  import { useRequest } from 'vue-request'
  import { useRoute, useRouter } from 'vue-router'

  import GPagination from '@/components/GPagination/index.vue'
  import useList from '@/hooks/use-list'
  import { modelLibraryApi } from '@/services/api'
  import { replaceEmptyStr } from '@/utils'
  import { filterTableColumns } from '@/utils/ant-component'
  import { checkPermissions } from '@/utils/share'

  import addVersionModal from '../list/components/addVersionModal.vue'
  import modelEvaluationModal from './components/modelEvaluationModal.vue'
  import OfflineDeploymentModal from './components/offlineDeploymentModal.vue'

  export interface DetailsResponse {
    id: number
    name: string
    url: string
  }
  type Key = string | number

  //表格
  interface PageForm {
    modelBaseId: string
    version: string
    source: number | string
    columns: 'createTime' | 'size' | ''
    order: 'desc' | 'asc'
  }
  interface IUser {
    createTime: string
    name: string
    id: number
    size: number
    description: string
    version: string
    modelFileUrl: string
    visualizeFilePath: string
  }
  interface FormState {
    description: string
  }
  type TableDataType = {
    key: string
    name: string
    age: number
    address: string
  }

  const sourceOptions = [
    { label: '用户上传', value: 0 },
    { label: '公开模型发布', value: 1 },
    { label: '自定义模型发布', value: 2 },
    { label: '我的算法发布', value: 3 },
    { label: '预置算法发布', value: 4 }
  ]

  const route = useRoute()
  const router = useRouter()
  const { id } = route.params as { id: string }
  const datasetName = ref<string>('')
  const detailInfo = ref<any>()

  const crumbs = computed(() => {
    return [{ path: '/my-model-manage/list', name: `模型管理 ` }, { name: `${datasetName.value || ''}` }]
  })

  const addVersionModalRef = ref()
  const addVersion = () => {
    addVersionModalRef.value?.open(id, detailInfo.value.url)
  }

  const offlineDeploymentModalRef = ref()
  const modelEvaluationModalRef = ref()
  const operation = (type: number, item: any) => {
    console.log(type, item)
    switch (type) {
      case 1:
        console.log('下载')
        return
      case 2:
        // console.log('在线部署')
        router.push('/my-model-manage/online-deployment/1')
        return
      case 3:
        offlineDeploymentModalRef.value?.open()
        // console.log('离线部署')
        return
      case 4:
        // console.log('删除')
        Modal.confirm({
          title: '确定删除?',
          content: '所选数据删除后不可恢复',
          cancelText: '取消',
          okText: '确定',
          centered: true,
          onOk: async () => {
            await modelLibraryApi.delModalVersion({ id: item?.id, modelBaseId: id }, { isAddUid: true })
            message.success('删除成功')
            getDetailsListData({ offset: 1 })
          }
        })
        return
      case 5:
        console.log('模型评估')
        modelEvaluationModalRef.value?.open()
        return
      default:
        console.log('666')
    }
  }

  // 选择表格行
  const tableColumns = ref(
    filterTableColumns([
      {
        title: '版本号',
        dataIndex: 'version',
        width: 200
      },
      {
        title: '来源',
        dataIndex: 'source',
        width: 200
      },
      {
        title: '镜像',
        dataIndex: 'imageName',
        width: 308
      },
      {
        title: '框架',
        dataIndex: 'frame',
        width: 120
      },
      {
        title: '描述',
        dataIndex: 'description'
      },
      {
        title: '创建时间',
        isSort: true,
        dataIndex: 'createTime',
        width: 200
      },
      {
        title: '操作',
        width: 80,
        dataIndex: 'tools'
      }
    ])
  )
  const {
    pageForm,
    dataList: detailList,
    getDataList: getDetailsListData,
    loading
  } = useList<PageForm, IUser>(modelLibraryApi.detailsList, {
    modelBaseId: id,
    version: '',
    source: '',
    columns: '',
    order: 'desc'
  })

  //根据id查询详情
  const { loading: getDetailLoading, runAsync: getDetail } = useRequest<ResponseData<DetailsResponse>>(modelLibraryApi.getModelInfo, {
    onSuccess: ({ data }) => {
      datasetName.value = data.name
      detailInfo.value = data
    }
  })
  const detailLoading = computed(() => loading.value || getDetailLoading.value)

  const tableChange: TableProps<TableDataType>['onChange'] = (pagination: any, filters: any, sorter: any) => {
    pageForm.value.columns = sorter.field
    pageForm.value.order = sorter.order === 'ascend' ? 'asc' : 'desc'
    if (!sorter.order) {
      pageForm.value.columns = 'createTime'
      pageForm.value.order = 'desc'
    }
    getDetailsListData({ offset: 1 })
  }

  const init = async () => {
    await getDetailsListData()
    await getDetail({ id })
  }
  init()
</script>
<style lang="less" scoped>
  .page {
    display: flex;
    justify-content: center;
    width: 100%;
  }

  .subheading-text {
    margin-top: 12px;
    height: 24px;
  }

  .search-input {
    padding: 12px 0;
  }

  .modal-label {
    font-weight: 700;
    font-size: 16px;
    line-height: 24px;
    color: rgba(16, 16, 20, 0.95);
  }

  .footer {
    display: flex;
    align-items: center;
    padding: 8px 0;
    width: 100%;
    height: 52px;
    font-size: 14px;
    text-align: center;
    background: #fff;
    box-shadow: 0 -1px 3px rgba(37, 37, 45, 0.2);
    line-height: 36px;

    .deselectAll {
      width: 124px;
      height: 100%;
      color: #009cf8;
      border-right: 1px solid #e8e8eb;

      &:hover {
        cursor: pointer;
      }
    }

    .numberOfSelected {
      width: 121px;
      height: 100%;
      color: rgba(16, 16, 20, 0.95);
    }

    .batchDeletion {
      margin-right: 8px;
      width: 88px;
      height: 36px;
      background: #fff;
      border: 1px solid #d9d9db;
      border-radius: 6px;
      box-shadow: 0 2px 0 rgba(0, 0, 0, 0.043);

      &:hover {
        cursor: pointer;
      }
    }

    .batchDownload {
      width: 88px;
      height: 36px;
      background: #fff;
      border: 1px solid #d9d9db;
      border-radius: 6px;
      box-shadow: 0 2px 0 rgba(0, 0, 0, 0.043);

      &:hover {
        cursor: pointer;
      }
    }
  }
</style>
